# -*- coding: utf-8 -*-
"""
Date: 2021-12-13
Author: J z
"""
import datetime

import jwt

from app.user.component.core.base_component import BaseComponent
from common.tips_info import CodeInfo
from framework.dal.gameconfig.query import getProfile
from framework.dal.repository_impl import RoleRepository
from framework.firefly_dc.error_handle import GameException
from framework.firefly_dc.global_errcode import GlobalErrCode


class AuthComponent(BaseComponent):

    def login(self, mobile, password):

        result = dict()
        # 检验参数

        # 检测账号密码(数据库密码需解密)
        role_record = RoleRepository.get_by_mobile(mobile)
        if not role_record or role_record.password != password:
            raise GameException(stat=CodeInfo.PassWordError)

        # 登录成功: 下发token及刷新token(15天过期)

        # 客户端访问需要认证的接口时，携带 Access Token
        # 如果 Access Token 没有过期，服务端鉴权后返回给客户端需要的数据
        # 如果携带 Access Token 访问需要认证的接口时鉴权失败（例如返回 401 错误），则客户端使用 Refresh Token 向刷新接口申请新的 Access Token
        # 如果 Refresh Token 没有过期，服务端向客户端下发新的 Access Token
        # 客户端使用新的 Access Token 访问需要认证的接口
        getProfile('ConfigEnvSet', Id=1)
        result['Token'] = self.get_auth_token(role_record.role_guid)
        result['RefreshToken'] = self.get_auth_token(role_record.role_guid, refresh_token=True)
        result['Role'] = role_record.asdict()

        return result

    def register(self, mobile, password):
        """
        注册
        :param mobile :
        :param password :
        """
        result = dict()
        _role = RoleRepository.get_by_mobile(mobile)
        if _role:
            raise GameException(CodeInfo.ExistMobile)

        try:
            role = RoleRepository.create(mobile, password)
            result['Role'] = role.asdict()
            result['Token'] = self.get_auth_token(_role.role_guid)
            result['RefreshToken'] = self.get_auth_token(_role.role_guid, refresh_token=True)
        except:
            pass

        return result

    def refresh_token(self, refresh_token):
        """
        根据刷新Token下发新认证token

        :param refresh_token : 刷新Token
        """

        result = dict()
        token_stat = 0

        try:
            payload = jwt.decode(
                jwt=refresh_token,
                key="test",
                algorithms=["HS256"],
            )
            rid = payload['rid']

            # 签发新token(解密后一定含有rid)
            result['Token'] = self.get_auth_token(rid)
            result['RoleGuid'] = rid

        except:
            # 刷新token失效
            token_stat = GlobalErrCode.Token_ERROR

        return result, token_stat

    @staticmethod
    def get_auth_token(role_guid, refresh_token=False):
        """
        获取认证token
        """

        exp_time_seconds = 12222222 if refresh_token else 222222222

        payload = {
            "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=exp_time_seconds),
            "rid": role_guid
        }

        token = jwt.encode(
            payload=payload,
            key="test",  # 签名使用
            algorithm="HS256"
        )
        return token
